package com.intexh.quickandroid.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.intexh.quickandroid.R;
import com.intexh.quickandroid.module.login.LoginActivity;
import com.intexh.quickandroid.utils.InputMethodUtils;
import com.intexh.quickandroid.utils.ToastUtil;


public abstract class BaseActivity extends AppCompatActivity {

    private ProgressDialog loadingDialog;
    private TextView loading_tv;
    protected Context mContext;
    private View dialogLayout;
    private AlertDialog hintDialog;
    public boolean isDestory;
    private boolean isShowingTokanHint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainApplication.addActivity(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mContext = this;
    }

    //沉浸式状态栏
    public void translucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentStatus | flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }

    protected <T extends View> T $(int resId) {
        return (T) super.findViewById(resId);
    }

    public <T extends View> T $(int resId, View rootView) {
        if (rootView == null) {
            throw new IllegalStateException("Content view not yet created");
        }
        return (T) rootView.findViewById(resId);
    }

    @Override
    protected void onStop() {
        super.onStop();
        InputMethodUtils.hideSoftInput(this);
    }


    protected void onDestroy() {
        /*//强制content view尽早释放
        setContentView(new View(this));*/ //CP
        isDestory = true;
        hideProgress();
        if (hintDialog != null && hintDialog.isShowing()) {
            hintDialog.dismiss();
        }
        MainApplication.removeActivity(this);
        super.onDestroy();
        System.gc();
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(getApplicationContext(), clz));
    }

    public void startActivityForResult(Class<?> clz, int requestCode) {
        startActivityForResult(new Intent(getApplicationContext(), clz), requestCode);
    }

    /**
     * [携带数据的页面跳转]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void showToast(String message) {
        ToastUtil.showToast(mContext, message);
    }

    public void logE(String message) {
        ToastUtil.showToast(mContext, message);
    }


    public void showProgress(String message) {
        showProgress(message, true);
    }

    public void showProgress() {
        showProgress("请稍后...", true);
    }

    public void showProgress(boolean isCancelable) {
        showProgress("请稍后...", isCancelable);
    }

    public void showProgress(String message, boolean isCancelable) {
        if (loadingDialog == null) {
            LayoutInflater inflater = LayoutInflater.from(this);
            // 得到加载view
            dialogLayout = inflater.inflate(R.layout.layout_view_loading, null);
            loading_tv = (TextView) dialogLayout.findViewById(R.id.loading_tv);
            loadingDialog = new ProgressDialog(this, R.style.transparent_dialog_theme);
            loadingDialog.setCancelable(isCancelable);
            loadingDialog.setCanceledOnTouchOutside(false);
            loadingDialog.show();
            loadingDialog.setContentView(dialogLayout);// 设置布局 需要在show后执行 否则报requestFeature() must be called before adding content
            loadingDialog.setOnDismissListener(dialog -> onLoadingDismiss());
        }
        loading_tv.setText(message);
        if (getBaseContext() != null && !loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    public void onLoadingDismiss() {

    }

    public void hideProgress() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    public void showHintDialog(String message) {
        if (isDestory) return;
        if (hintDialog == null) {
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mContext);
            builder.setMessage(message);
//        builder.setNegativeButton("取消", null);
            builder.setPositiveButton("确定", null);
            hintDialog = builder.show();
        } else {
            hintDialog.setMessage(message);
            hintDialog.show();
        }
    }

    /**
     * 获取验证码倒计时更新的方法
     */
    public void countDownReSend(final TextView textView, long sec) {
        if (textView == null) return;
        showToast("验证码发送成功，请注意查收");
        textView.setTag(textView.getTextColors());
        textView.setEnabled(false);
        new CountDownTimer(sec * 1000, 1000) {
            public void onTick(long millisUntilFinished) {
                if (isDestory) {
                    cancel();
                    return;
                }
                textView.setText((millisUntilFinished / 1000) + "秒倒计时");
            }

            public void onFinish() {
                if (isDestory)
                    return;
                textView.setText("重新获取");
                textView.setEnabled(true);
                textView.setSelected(false);
            }
        }.start();
    }

    //弹出登录失效弹窗
    public void showTokenInvalidHintDialog() {
        if (isShowingTokanHint) return;
        if(isDestory)return;
        if(mContext==null)return;
        isShowingTokanHint = true;
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage("您的登录凭证已失效，请重新登录！");
        builder.setCancelable(false);
        builder.setOnDismissListener(dialog -> {
            isShowingTokanHint = false;
        });
        builder.setNegativeButton("", (dialog, which) -> {

        });
        builder.setPositiveButton("登录", (dialog, which) -> {
            startActivity(LoginActivity.class);
        });
        builder.show();
    }
}
